package com.ribbon;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class MyRibbonRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties ndp;
    @Autowired
    private NacosServiceManager nam;
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        //获取服务名
        BaseLoadBalancer lb = (BaseLoadBalancer) getLoadBalancer();
        String name = lb.getName();
        //获取当前的服务信息
        String clusterName = ndp.getClusterName();
        String group = ndp.getGroup();
        NamingService namingService = nam.getNamingService(ndp.getNacosProperties());
        //获取实例
        try {
            List<Instance> instances = namingService.selectInstances(name, group, true);
            List<Instance> list = instances.stream().filter(i -> i.getClusterName().equals(clusterName)).collect(Collectors.toList());
            instances = list==null||list.size()==0?instances:list;
            //使用内部类继承Balancer，获取其protect方法
            return new NacosServer(MyWeightRule.getByRandomWeight(instances));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static class MyWeightRule extends Balancer {
        public static Instance getByRandomWeight(List<Instance> hosts) {
            return Balancer.getHostByRandomWeight(hosts);
        }
    }
}
